package com.zhsj.OkeHomeConsumption.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyApplication;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * @Description: TODO 网络访问工具类
 */
public class HttpClient {

    private static final int CONNECT_TIME_OUT = 5;
    private static final int WRITE_TIME_OUT = 60;
    private static final int READ_TIME_OUT = 60;
    private static final int MAX_REQUESTS_PER_HOST = 10;
    private static final String TAG = HttpClient.class.getSimpleName();
    private static OkHttpClient client;
    public static final MediaType JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    public static final MediaType JSONT = MediaType.parse("application/json; charset=utf-8");

    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
        // builder.networkInterceptors().add(new LoggingInterceptor());
        client = builder.build();
        client.dispatcher().setMaxRequestsPerHost(MAX_REQUESTS_PER_HOST);
    }

    static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            Log.i(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
                    request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            Log.i(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(),
                    (t2 - t1) / 1e6d, response.headers()));
            return response;
        }
    }

    public static boolean isNetworkAvailable() {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
        } catch (Exception e) {
            Log.v("ConnectivityManager", e.getMessage());
        }
        return false;
    }

    /**
     * @param @param url
     * @param @param param
     * @param @param httpResponseHandler
     * @return void    返回类型
     * @throws
     * @Title: get
     * @Description: TODO
     */
    public static void get(String url, Map<String, String> param, final HttpResponseHandler httpResponseHandler) {
        if (!isNetworkAvailable()) {
            Toast.makeText(MyApplication.getContext(), "网络信号弱,请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        } if (param == null) {
            param = new HashMap<>();
        }
        // 请求url（baseUrl+参数）
        String doUrl = urlJoint(url, param);

//        Request request = null;
        Request request = new Request.Builder()
                // token
                .addHeader("token", Constants.TOKEN)
                // sign
                .addHeader("sign", Constants.SIGN)
                // 版本号
                .addHeader("v", Constants.APPVERSION)
                // 当前时间戳
                .addHeader("t", Constants.TIME)
                // DEVICEID
                .addHeader("deviceId", URLEntity.getInstance().getImei())
                // platform
                .addHeader("platform", Constants.PLAFORM)
                // 参数名：client，0表示合伙人端，1表示客户端
                .addHeader("client", Constants.CLIENT)
                .url(doUrl).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                httpResponseHandler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                httpResponseHandler.sendFailureMessage(call.request(), e);
            }
        });
    }
    /**
     * @param url    实际URL的path
     * @param params
     * @return
     */
    private static String urlJoint(String url, Map<String, String> params) {
        StringBuilder realURL = new StringBuilder();
        realURL = realURL.append(url);
        boolean isFirst = true;
        if (params == null) {
            params = new HashMap<>();
        } else {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                if (isFirst && !url.contains("?")) {
                    isFirst = false;
                    realURL.append("?");
                } else {
                    realURL.append("&");
                }
                realURL.append(entry.getKey());
                realURL.append("=");
                if (entry.getValue() == null) {
                    realURL.append(" ");
                } else {
                    realURL.append(entry.getValue());
                }

            }
        }

        return realURL.toString();
    }

    /**
     * @param @param url
     * @param @param param
     * @param @param handler
     * @return void    返回类型
     * @throws
     * @Title: post
     * @Description: TODO
     */
    public static void post(String url, final Map<String, String> param, final HttpResponseHandler handler) {
        if (!isNetworkAvailable()) {
            Toast.makeText(MyApplication.getContext(), "网络信号弱,请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.e("lipeng", "访问接口" + url);
        RequestBody body = new RequestBody() {

            @Override
            public MediaType contentType() {
                // TODO Auto-generated method stub
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                // TODO Auto-generated method stub
                DataOutputStream outputStream = new DataOutputStream(sink.outputStream());
                JSONObject postParamObj = new JSONObject();
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    try {
                        postParamObj.put(entry.getKey(), StringUtils.enCodeRUL(entry.getValue()));
                        outputStream.writeBytes(entry.getKey() + "=" + StringUtils.enCodeRUL(entry.getValue()) + "&");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        };
        Request request = new Request.Builder()
                // token
                .addHeader("token", Constants.TOKEN)
                // sign
                .addHeader("sign", Constants.SIGN)
                // 版本号
                .addHeader("v", Constants.APPVERSION)
                // 当前时间戳
                .addHeader("t", Constants.TIME)
                // DEVICEID
                .addHeader("deviceId", URLEntity.getInstance().getImei())
                // platform
                .addHeader("platform", Constants.PLAFORM)
                // deviceToken(umeng push)
                .addHeader("deviceToken", Constants.DEVICETOKEN)
                // 参数名：client，0表示合伙人端，1表示客户端
                .addHeader("client", Constants.CLIENT).url(url).post(body).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendFailureMessage(call.request(), e);
            }
        });
    }

    public static void posttwo(String url, final String param, final HttpResponseHandler handler) {
        if (!isNetworkAvailable()) {
            Toast.makeText(MyApplication.getContext(), "网络信号弱,请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.e("lipeng", "访问接口" + url);
        RequestBody body = FormBody.create(MediaType.parse("application/json"), param);
        Request request = new Request.Builder()
                // token
                .addHeader("token", Constants.TOKEN)
                // sign
                .addHeader("sign", Constants.SIGN)
                // 版本号
                .addHeader("v", Constants.APPVERSION)
                // 当前时间戳
                .addHeader("t", Constants.TIME)
                // DEVICEID
                .addHeader("deviceId", URLEntity.getInstance().getImei())
                // platform
                .addHeader("platform", Constants.PLAFORM)
                // deviceToken(umeng push)
                .addHeader("deviceToken", Constants.DEVICETOKEN)
                // 参数名：client，0表示合伙人端，1表示客户端
                .addHeader("client", Constants.CLIENT).url(url).post(body).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendFailureMessage(call.request(), e);
            }
        });
    }

    /**
     * @param @param  url 接口地址
     * @param @param  file 资源mediaType类型:比如 MediaType.parse("image/png");
     * @param @param  mediaType
     * @param @param  handler 回调方法,在子线程,更新UI要post到主线程
     * @param @return
     * @return void    返回类型
     * @throws
     * @Title: uploadFile
     * @Description: TODO 上传文件
     */
    public static void uploadFile(String url, File file, MediaType mediaType, final HttpResponseHandler handler) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (!file.exists() || TextUtils.isEmpty(url)) {
            return;
        }
        builder.addFormDataPart("file", file.getName(), RequestBody.create(mediaType, file));
        //构建请求体
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                // token
                .addHeader("token", Constants.TOKEN)
                // sign
                .addHeader("sign", Constants.SIGN)
                // 版本号
                .addHeader("v", Constants.APPVERSION)
                // 当前时间戳
                .addHeader("t", Constants.TIME)
                // DEVICEID
                .addHeader("deviceId", URLEntity.getInstance().getImei())
                // platform
                .addHeader("deviceToken", Constants.DEVICETOKEN)
                .addHeader("platform", Constants.PLAFORM)
                // 参数名：client，0表示合伙人端，1表示客户端
                .addHeader("client", Constants.CLIENT).url(url).post(requestBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendFailureMessage(call.request(), e);
            }
        });
    }

       public static void uploadFiles(String url, List<File> files, MediaType mediaType, final HttpResponseHandler handler) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (!files.get(0).exists() || TextUtils.isEmpty(url)) {
            return;
        }
        for (int i = 0; i < files.size(); i ++) {
            builder.addFormDataPart("file" + i, files.get(i).getName(), RequestBody.create(mediaType, files.get(i)));
        }
        //构建请求体
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                // token
                .addHeader("token", Constants.TOKEN)
                // sign
                .addHeader("sign", Constants.SIGN)
                // 版本号
                .addHeader("v", Constants.APPVERSION)
                // 当前时间戳
                .addHeader("t", Constants.TIME)
                // DEVICEID
                .addHeader("deviceId", URLEntity.getInstance().getImei())
                // platform
                .addHeader("platform", Constants.PLAFORM)
                // deviceToken(umeng push)
                .addHeader("deviceToken", Constants.DEVICETOKEN)
                // 参数名：client，0表示合伙人端，1表示客户端
                .addHeader("client", Constants.CLIENT).addHeader("Connection", "close").url(url).post(requestBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handler.sendSuccessMessage(response);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendFailureMessage(call.request(), e);
            }
        });
    }
}
